import { login, getInfo ,register} from '@/api/user'
import {getToken, setToken, removeToken,
  getUserSign, setUserSign,removeUserSign,} from '@/utils/auth'
import { resetRouter } from '@/router'
import tim from "@/tim";
import store from "@/store";

const getDefaultState = () => {
  return {
    // 令牌
    token: getToken(),
    name: '', // 名称
    avatar: '', // 头像
    id:'', // 账号
    sex:'', // 性别
    signature:'', // 签名
    phone:'', // 电话
    userSign:getUserSign() // 腾讯im签名

  }
}

const state = getDefaultState()

const getters = {
  token: state => state.token,
  avatar: state => state.avatar,
  name: state => state.name,
  id: state => state.id,
  signature: state => state.signature,

  sex: state => {
    if(state.sex === 1){
      return '男'
    }else if(state.sex === 2){
      return '女'
    }else{
      return '未设置性别'
    }
  },
  phone: state => state.phone,

  userSign: state => state.userSign,
}

const mutations = {
  RESET_STATE: (state) => {
    // Object.assign() 方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ID:(state,id)=>{
    state.id = id
  },
  SET_SEX:(state,sex)=>{
    state.sex = sex
  },
  SET_SIGNATURE:(state,signature)=>{
    state.signature = signature
  },
  SET_PHONE:(state,phone)=>{
    state.phone = phone
  },
  updateUserSign(state,userSign){
    state.userSign = userSign
  }
}

const actions = {
  // user login 用户登陆
    login({ commit,dispatch }, userInfo) {
    const { userid, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ userid: userid.trim(), password: password }).then(response => {
        const { content } = response
        setUserSign(content.userSign) // 保存tim签名到cookie中
        setToken(content.token)
        commit('SET_TOKEN', content.token)
        commit('SET_NAME',content.user.username)
        commit('SET_AVATAR',content.user.avatar)
        commit('SET_ID',content.user.userid)
        commit('SET_SEX',content.user.sex)
        commit('updateUserSign',content.userSign)
        commit('SET_SIGNATURE',content.user.signature)
        commit('SET_PHONE', content.user.phone);
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 用户注册
  signUp({commit},registerInfo){
    console.log(registerInfo)
    const {avatar, username, userid, password, status} = registerInfo;
    return new Promise((resolve,reject)=>{
      register({avatar, username, userid, password, status}).then(res=>{
        const {content} = res
        if(status === 'ONLINE'){
          setUserSign(content.userSign)
          commit('SET_TOKEN',content.token)
          commit('updateUserSign',content.userSign)
          commit('SET_NAME',content.user.username)
          commit('SET_AVATAR',content.user.avatar)
          commit('SET_ID',content.user.userid)
          commit('SET_SEX',content.user.sex)
          commit('SET_SIGNATURE',content.user.signature)
          commit('SET_PHONE',content.user.phone)
          setToken(content.token)
        }
        resolve()
      }).catch(err=>{
        reject(err)
      })
    })
  },

  // get user info （获取用户信息）
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      // 向服务端发送请求，携带token，获取用户信息
      getInfo(state.token).then(response => {
        const {content} = response
        if (!content) {
          return reject('验证失败，请重新登录。')
        }
        const {user} = content
        console.log(user)
        commit('SET_NAME', user.username) // 初始化用户的名称
        commit('SET_AVATAR', user.avatar) // 初始化用户的头像
        commit('SET_ID',user.userid)
        commit('SET_SEX', user.sex)
        commit('SET_SIGNATURE', user.signature)
        commit('SET_PHONE', user.phone)
        setUserSign(content.userSign) // 保存tim签名到cookie中
        resolve(content)
      }).catch(error => {
        reject(error)
      })
    });
  },

  // user logout
  logout({ commit}) {
    return new Promise((resolve) => {
      // 判断 tim SDK 是否ready
      console.log(store.state.chat.isSDKReady)
      if(store.state.chat.isSDKReady){
        tim.logout().then(()=>{
          console.log("退出登录IM成功");
          removeToken() // must remove  token  first
          resetRouter()
          removeUserSign() // 清除tim 签名
          commit('RESET_STATE')
          commit('chat/showMessage',{
            message:'退出登录成功',
            type:'success'
          },{root:true})
          resolve()
        }).catch(err=>{
          commit('chat/showMessage',{
            message:'退出登录TIM失败：'+err.message,
            type:'error'
          },{root:true})
        })
      }else{
        removeToken() // must remove  token  first
        resetRouter()
        removeUserSign() // 清除tim 签名
        commit('RESET_STATE')
        resolve()
      }
    })
  },

  // remove token // 删除token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first（必须先删除token）
      commit('RESET_STATE') // 提交
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  getters,
  actions
}

